import Vue from 'vue';
import { Loading } from 'element-ui';
import $ from 'jquery';
import { errors } from '../api/error'
const host = process.env.VUE_APP_API_BASE;
let baseUrl = host;
let timeout = 1200000;
export const global = {
  get: function (url, options, sucCb, errorCb, timeOut, isLoading = true, sign) {
    if (!url) {
      return false;
    }
    let reqUrl = baseUrl + url;
    let token_dasserv = sessionStorage.getItem('token_crec')
    let context = {
      forwardType: 1,
    }
    let SOURCENAME = '';
    if (context.forwardType == 1) {
      SOURCENAME = "PC-OPERATORMOBILE"
    } else {
      SOURCENAME = "PC-STORE"
    }
    //遮罩层
    if (isLoading) {
      var loadingInstance = Loading.service({
        text: "加载中"
      });
    }
    $.ajax({
      url: reqUrl,
      data: options,
      dateType: "json",
      type: "get",
      headers: {
        token_dasserv:token_dasserv
      },
      timeout: timeOut ? timeOut : timeout,
      success: function (response) {
        sucCb(response);
        if (isLoading) {
          loadingInstance.close();
        }
      },
      error: function (response, jqXHR, textStatus, errorThrown) {
        if (textStatus == "timeout") {
          let msg = confirm('网络故障，是否重新加载?');
          if (msg) {
            location.reload();
          }
          if (isLoading) {
            loadingInstance.close();
          }
        } else {
          errorCb(response);
          if (isLoading) {
            loadingInstance.close();
          }
        }
      },
    });
  },
  post: function (url, body, contentType, options, sucCb, errorCb, sign = false, isLoading = true, uptype = false, timeOut) {
    if (!url) {
      return false;
    }
    let reqUrl = baseUrl + url;
    let SOURCENAME = '';
    let context = {
      forwardType: 1,
    }
    if (context.forwardType == 1) {
      SOURCENAME = "PC-OPERATORMOBILE";
    } else {
      SOURCENAME = "PC-STORE";
    }
    //遮罩层
    if (isLoading) {
      if (sign) {
        var loadingInstance = Loading.service({
          text: "正在上传，请勿离开或刷新此页面！"
        })
      } else {
        var loadingInstance = Loading.service({
          text: "加载中"
        });
      }
    }
    if (uptype) {
      $.ajax({
        url: reqUrl,
        xhrFields: {
          withCredentials: true
        },
        contentType: false,
        data: options,
        processData: false,
        type: "post",
        timeout: timeOut ? timeOut : timeout,
        success: function (response) {
          sucCb(response);
          if (isLoading) {
            loadingInstance.close();
          }
        },
        headers: {
          SOURCE: SOURCENAME
        },
        error: function (response, jqXHR, textStatus, errorThrown) {
          if (textStatus == "timeout") {
            let msg = confirm('网络故障，是否重新加载?');
            if (msg) {
              location.reload();
            }
            if (isLoading) {
              loadingInstance.close();
            }
          } else {
            errorCb(response);
            if (isLoading) {
              loadingInstance.close();
            }
          }
        },
      });
    } else {
      if (!contentType) {
        $.ajax({
          url: reqUrl,
          xhrFields: {
            withCredentials: true
          },
          headers: {
            SOURCE: SOURCENAME
          },
          data: options,
          dateType: "json",
          type: "post",
          timeout: timeOut ? timeOut : timeout,
          success: function (response) {
            sucCb(response);
            if (isLoading) {
              loadingInstance.close();
            }
          },
          error: function (response, jqXHR, textStatus, errorThrown) {
            if (textStatus == "timeout") {
              let msg = confirm('网络故障，是否重新加载?');
              if (msg) {
                location.reload();
              }
              if (isLoading) {
                loadingInstance.close();
              }
            } else {
              errorCb(response);
              if (isLoading) {
                loadingInstance.close();
              }
            }
          },
        });
      } else {
        $.ajax({
          url: reqUrl,
          xhrFields: {
            withCredentials: true
          },
          contentType: "application/json; charset=utf-8",
          data: options,
          dateType: "json",
          type: "post",
          timeout: timeOut ? timeOut : timeout,
          success: function (response) {
            sucCb(response);
            if (isLoading) {
              loadingInstance.close();
            }
          },
          headers: {
            SOURCE: SOURCENAME
          },
          error: function (response, jqXHR, textStatus, errorThrown) {
            if (textStatus == "timeout") {
              let msg = confirm('网络故障，是否重新加载?');
              if (msg) {
                location.reload();
              }
              if (isLoading) {
                loadingInstance.close();
              }
            } else {
              errorCb(response);
              if (isLoading) {
                loadingInstance.close();
              }
            }
          },
        });
      }
    }

  },
  postupload: function (url, body, options, sucCb, errorCb, timeOut, isLoading = true, ) {
    // this.log("传入的参数为：", options)
    // this.log("判断传参是否为object类型，如果是就克隆传参,如果不是就复制传参并转成object类型参数")
    let newOptions;
    newOptions = options
    if (!url) {
      return false;
    }
    let reqUrl = baseUrl + url;
    // let reqUrl = url;
    isLoading = true
    //遮罩层
    if (isLoading) {
      if (url == "order/publish/batch") {
        var loadingInstance = Loading.service({
          text: "正在上报订单，请勿离开或刷新此页面！"
        });
      } else if (url == 'activity/order/import/addOrUpdate') {
        var isLoading = undefined;

      } else {
        var loadingInstance = Loading.service({
          text: "加载中"
        });
      }
    }
    $.ajax({
      url: reqUrl,
      // 跨域 保证sessionid 一致
      // xhrFields: {
      //   withCredentials: true
      // },
      data: newOptions,
      crossDomain: true,
      contentType: false,
      processData: false,
      mimeType: "multipart/form-data",
      type: "post",
      headers: {
        // source: 0,//添加的固定值
      },
      timeout: timeOut ? timeOut : timeout,
      success: function (response) {
        sucCb(response);
        if (isLoading) {
          loadingInstance.close();
        }
      },
      error: function (response, jqXHR, textStatus, errorThrown) {
        if (textStatus == "timeout") {
          let msg = confirm('网络故障，是否重新加载?');
          if (msg) {
            location.reload();
          }
          if (isLoading) {
            loadingInstance.close();
          }
        } else {
          errorCb(response);
          if (isLoading) {
            loadingInstance.close();
          }
        }
      },
    });
  },
  put: function (url, body, options, sucCb, errorCb, timeOut, isLoading = true, sign) {
    if (!url) {
      return false;
    }
    let reqUrl = baseUrl + url;
    //遮罩层
    if (isLoading) {
      var loadingInstance = Loading.service({
        text: "加载中"
      });
    }
    // let context = JSON.parse(sessionStorage.getItem('context'))
    let context = {
      forwardType: 1,
    }
    let SOURCENAME = '';
    if (context.forwardType == 1) {
      SOURCENAME = "PC-OPERATORMOBILE"
    } else {
      SOURCENAME = "PC-STORE"
    }
    $.ajax({
      url: reqUrl,
      xhrFields: {
        withCredentials: true
      },
      data: options,
      contentType: "application/json; charset=utf-8",
      dateType: "json",
      type: "put",
      headers: {
        SOURCE: SOURCENAME
      },
      timeout: timeOut ? timeOut : timeout,
      success: function (response) {
        sucCb(response);
        if (isLoading) {
          loadingInstance.close();
        }
      },
      error: function (response, jqXHR, textStatus, errorThrown) {
        if (textStatus == "timeout") {
          let msg = confirm('网络故障，是否重新加载?');
          if (msg) {
            location.reload();
          }
          if (isLoading) {
            loadingInstance.close();
          }
        } else {
          errorCb(response);
          if (isLoading) {
            loadingInstance.close();
          }
        }
      },
    });
  },
  delete: function (url, body, options, sucCb, errorCb, timeOut, isLoading = true, sign) {
    if (!url) {
      return false;
    }
    let reqUrl = baseUrl + url;
    //遮罩层
    if (isLoading) {
      var loadingInstance = Loading.service({
        text: "加载中"
      });
    }
    // let context = JSON.parse(sessionStorage.getItem('context'))
    let SOURCENAME = '';
    let context = {
      forwardType: 1,
    }
    if (context.forwardType == 1) {
      SOURCENAME = "PC-OPERATORMOBILE"
    } else {
      SOURCENAME = "PC-STORE"
    }
    $.ajax({
      url: reqUrl,
      xhrFields: {
        withCredentials: true
      },
      data: options,
      contentType: "application/json; charset=utf-8",
      dateType: "json",
      type: "delete",
      headers: {
        SOURCE: SOURCENAME
      },
      timeout: timeOut ? timeOut : timeout,
      success: function (response) {
        sucCb(response);
        if (isLoading) {
          loadingInstance.close();
        }
      },
      error: function (response, jqXHR, textStatus, errorThrown) {
        if (textStatus == "timeout") {
          let msg = confirm('网络故障，是否重新加载?');
          if (msg) {
            location.reload();
          }
          if (isLoading) {
            loadingInstance.close();
          }
        } else {
          errorCb(response);
          if (isLoading) {
            loadingInstance.close();
          }
        }
      },
    });
  },
  openTip: function (obj, msg, type) {
    obj.$message({
      message: msg,
      showClose: true, //{ Boolean  } -可选 提示信息是否可手动关闭
      type: type
    });
  },
  addActive: function (opt) {
    let obj = $('#' + opt);
    if (obj) {
      obj.addClass('is-active');
    }
  },
  getArea: function (url, sucCb, errorCb, timeOut, isLoading = true, ) {
    let reqUrl = baseUrl + url;
    //遮罩层
    if (isLoading) {
      var loadingInstance = Loading.service({
        text: "加载中"
      });
    }
    $.ajax({
      url: reqUrl,
      xhrFields: {
        withCredentials: true
      },
      dateType: "json",
      type: "get",
      timeout: timeOut ? timeOut : timeout,
      success: function (response) {
        sucCb(response);
        if (isLoading) {
          loadingInstance.close();
        }
      },
      error: function (response, jqXHR, textStatus, errorThrown) {
        if (textStatus == "timeout") {
          let msg = confirm('网络故障，是否重新加载?');
          if (msg) {
            location.reload();
          }
          if (isLoading) {
            loadingInstance.close();
          }
        } else {
          errorCb(response);
          if (isLoading) {
            loadingInstance.close();
          }
        }
      },
    });
  },
  uuid: function (len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  },
  errorToLogin: function (obj, res) {
    let url = process.env.VUE_APP_BASE_API + 'portal/#/support';
    if (res.msg + res.data == "登录超时") {
      // obj.$router.push('/ssoLogin');
      sessionStorage.clear("context");
      window.open(url, "_black");
    } else {
      if (typeof (res) == 'string') {
        res = JSON.parse(res)
      }
      if (res.code == 1 || res.code == 2 || res.code == 3 || res.code == 4 || res.code == 5) {
        sessionStorage.clear("context");
        window.open(url, "_black");
        if (res.code == 2) {
          this.openTip(obj, "验证信息超时，请重新登录", 'info');
        }
      } else if (res.code == -1) {
        this.openTip(obj, "网络繁忙,请稍后再试", 'error');
      } else {
        res.data = res.data ? res.data : '';
        if (res.msg) {
          obj.$message({
            message: res.msg + res.data,
            showClose: true, //{ Boolean  } -可选 提示信息是否可手动关闭
            type: 'error'
          });
        } else {
          obj.$message({
            message: res.message + res.data,
            showClose: true, //{ Boolean  } -可选 提示信息是否可手动关闭
            type: 'error'
          });
        }
      }
    }
  },
  exception: function (code, message) {
    const list = errors.filter(e => {
      return e.code === code
    })
    if (list.length === 0) {
      return message
    } else {
      return list[0].message
    }
  },

  /**
   * @param error error code 500 跳转到error页面
   */
  servicerError: function (obj, error) {
    if (error.code == 500) {
      obj.$router.push('/error');
    }
  },
  /**
   * 导出excel表格
   * @param  theader 表头
   * @param  filterVal table表格中对应的属性名
   * @param  data   表格数据
   * @param  tableName 导出表格名称
   */
  exportExcel: function (theader, filterVal, data, tableName) {
    require.ensure([], () => {
      const list = data.map(v => filterVal.map(j => v[j]));
      export_json_to_excel(theader, list, tableName);
    })
  },
  dateToSecond: function (param) {
    let now_str = param.replace(/:/g, '-'); //处理的时分秒（这个根据需要选择）
    now_str = now_str.replace(/ /g, '-'); //处理空格
    let arrs = now_str.split("-"); //分割成数组
    let newTime = new Date(parseInt(arrs[0]), parseInt(arrs[1]) - 1, parseInt(arrs[2]), parseInt(arrs[3]), parseInt(arrs[4]), parseInt(arrs[5]))
    return newTime;
  },
  deepCopy: function (obj) {
    if (obj === null) {
      return null
    }
    if (Array.isArray(obj)) {
      // 如果是数组
      const myArray = []
      for (let i = 0; i < obj.length; i++) {
        myArray.push(deepCopy(obj[i]))
      }
      return myArray
    } else if (typeof (obj) === 'object') {
      // 如果是对象
      const myObject = {}
      for (let key in obj) {
        myObject[key] = deepCopy(obj[key])
      }
      return myObject
    }
    return obj
  },
  changeType: function (data) {
    let len = data.length;
    for (let i = 0; i < len; i++) {
      switch (data[i].type) {
        case 1:
          data[i].userType = '系统管理员';
          break;
        case 2:
          data[i].userType = '门店管理员';
          break;
        case 3:
          data[i].userType = '公司管理员';
          break;
        default:
          break;
      }
      switch (data[i].isFinance) {
        case 0:
          data[i].isFinance = '否';
          break;
        case 1:
          data[i].isFinance = '是';
          break;
        default:
          break;
      }
    }
  },
  getIndex: function (arr, item) {
    var index = -1; // 先定义一个下标
    arr.forEach(function (res, i) { // 元素  下标
      if (res === item && index === -1) {
        index = i;
      }
    });
    return index;
  },

};
